using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using SubSonic.SqlGeneration.Schema;
using Webbness.Mvc.SubSonic;
using System.ComponentModel.DataAnnotations;

namespace Webbness.Mvc.Models
{
    public class Record : IRecord
    {
        private readonly Hashtable ForeignCache = new Hashtable();

        #region IRecord Members

        [SubSonicPrimaryKey]
        [HiddenInput]
        [ScaffoldInList(false)]
        [ScaffoldColumn(false)]
        public virtual int Id { get; set; }

        #endregion

        protected T GetForeign<T>(int key) where T : Record, new()
        {
            string relation = typeof (T).Name;
            var foreign = ForeignCache[relation] as T;
            if (foreign == null || foreign.Id != key)
            {
                foreign = Repository.Get<T>(key);
                ForeignCache[relation] = foreign;
            }
            return foreign;
        }

        protected int SetForeign<T>(T foreign) where T : Record, new()
        {
            string relation = typeof (T).Name;
            ForeignCache[relation] = foreign;
            return (foreign == null) ? 0 : foreign.Id;
        }

        protected List<T> GetForeignList<T>(Expression<Func<T, bool>> expression) where T : Record, new()
        {
            return GetForeignList(expression, false);
        }

        protected List<T> GetForeignList<T>(Expression<Func<T, bool>> expression, bool refresh) where T : Record, new()
        {
            string relation = "l-" + typeof (T).Name;
            var foreign = ForeignCache[relation] as List<T>;
            if (foreign == null || refresh)
            {
                foreign = Repository.Repo.Find(expression).ToList();
                ForeignCache[relation] = foreign;
            }
            return foreign;
        }
    }
}